package com.ark.service.service.impl;

import com.ark.common.domain.entity.sys.SysUser;
import com.ark.service.mapper.SysUserMapper;
import com.ark.service.service.SysUserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements SysUserService {

    @Resource
    private SysUserMapper userMapper;

    @Override
    public SysUser selectUserByUsername(String username) {
        return userMapper.selectUserByUsername(username);
    }

    @Override
    public IPage<SysUser> selectUserList(Page<SysUser> page, SysUser user) {
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getDelFlag,0)
                .eq(Objects.nonNull(user.getStatus()),SysUser::getStatus,user.getStatus())
                .like(Objects.nonNull(user.getUsername()),SysUser::getUsername,user.getUsername())
                .like(Objects.nonNull(user.getNickname()),SysUser::getNickname,user.getNickname())
                .like(Objects.nonNull(user.getEmail()),SysUser::getEmail,user.getEmail());

        return userMapper.selectPage(page,wrapper);
    }

    @Override
    @Transactional
    public boolean insertUser(SysUser user) {
        if (!save(user)){
            return false;
        }
        int index = userMapper.insertUserIdRoleId(user.getId(),3L);
        return index > 0;
    }

    @Override
    public boolean updateUser(SysUser user) {
        return lambdaUpdate().eq(SysUser::getId,user.getId()).update(user);
    }

    @Override
    public boolean deleteUserByIds(Long[] userIds) {
        return userMapper.deleteUserByIds(userIds)>0;
    }

    @Override
    public boolean emailExist(String email) {
        return lambdaQuery().eq(SysUser::getDelFlag,0).eq(SysUser::getEmail, email).exists();
    }

    @Override
    public boolean checkUserNameUnique(String username) {
        return lambdaQuery().eq(SysUser::getDelFlag,0).eq(SysUser::getUsername, username).exists();
    }

    @Override
    public SysUser selectUserById(Long userId) {
        return lambdaQuery().eq(SysUser::getId, userId).one();
    }
}
